from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask import Flask
import os
import pymysql

# 创建数据库实例
db = SQLAlchemy()
migrate = Migrate()

def init_db(app, use_mysql=True):
    """初始化数据库"""
    if use_mysql:
        # MySQL数据库配置
        app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:12345@localhost:3306/management_system?charset=utf8mb4'
        app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
            'pool_size': 10,
            'pool_recycle': 120,
            'pool_pre_ping': True,
            'echo': False
        }
    else:
        # SQLite数据库配置（备用）
        basedir = os.path.abspath(os.path.dirname(__file__))
        app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{os.path.join(basedir, "app.db")}'
    
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 初始化数据库
    db.init_app(app)
    migrate.init_app(app, db)
    
    # 创建所有表
    with app.app_context():
        try:
            db.create_all()
            print("数据库表创建成功")
        except Exception as e:
            print(f"数据库表创建失败: {e}")
            raise e
    
    return db

def create_database():
    """创建数据库（如果不存在）"""
    try:
        # 连接到MySQL服务器（不指定数据库）
        connection = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            password='12345',
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            # 创建数据库
            cursor.execute("CREATE DATABASE IF NOT EXISTS management_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            print("数据库 'management_system' 创建成功")
        
        connection.close()
        return True
    except Exception as e:
        print(f"创建数据库失败: {e}")
        return False

